package com.weetop.aklyscan.activity.sreach;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseActivity;
import com.weetop.aklyscan.base.BaseUrl;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.SearchBean;
import com.weetop.aklyscan.bean.SearchItemBean;
import com.weetop.aklyscan.bean.SerailBean;
import com.weetop.aklyscan.bean.SerailBean1;
import com.weetop.aklyscan.presenter.LocationSearchPresent;
import com.weetop.aklyscan.presenter.SearchPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.view.LocationSearchView;
import com.weetop.aklyscan.view.SearchView;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

public class SearchPositionActivity7 extends BaseActivity<SearchPresent> implements SearchView, BarcodeReader.BarcodeListener,
        BarcodeReader.TriggerListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.search_type)
    TextView search_type;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.zx_type)
    TextView zx_type;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.chaxun)
    TextView chaxun;
    @BindView(R.id.recyclerView1)
    RecyclerView recyclerView1;
    @BindView(R.id.recyclerView2)
    RecyclerView recyclerView2;
    @BindView(R.id.ll_zx)
    LinearLayout ll_zx;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.ll_bm)
    LinearLayout ll_bm;
    @BindView(R.id.ll_other)
    LinearLayout llOther;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.tv_time)
    TextView timeView;

    private ArrayList<SerailBean1.DataBean> data = new ArrayList<>();
    private ArrayList<SerailBean1.DataBean> data2 = new ArrayList<>();
    private CommonRecyclerAdapter<SerailBean1.DataBean> adapter;
    private CommonRecyclerAdapter<SerailBean1.DataBean> adapter2;
    private boolean isRefresh, isLoadMore;
    private int page = 1;
    private String keywords = "";
    private String goodsType = "1";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                text.setText((String) msg.obj);
                text.setBackgroundResource(R.drawable.et_grey);
                if (TextUtils.isEmpty(text2.getText().toString().trim()) && (int) type.getTag() == 1) {
                    text2.setBackgroundResource(R.drawable.et_yellow);
                }
//                onBarcodeEvent("K4002akny022126C3566");
            } else if (msg.what == 2) {
                text2.setText((String) msg.obj);
                text2.setBackgroundResource(R.drawable.et_grey);
            }
        }
    };

    @Override
    public void getInto57Success(BaseModel<SerailBean1> o) {
        int count = 0;
        if ((int) search_type.getTag() == 2) {
            data.clear();
            adapter.clear();
            data.addAll(o.getData().getList_data());
            adapter.addAll(o.getData().getList_data());
            for (SerailBean1.DataBean bean :
                    o.getData().getList_data()) {
                count += Integer.parseInt(bean.getCount_num());
            }
        } else {
            adapter2.clear();
            data2.clear();
            data2.addAll(o.getData().getList_data());
            adapter2.addAll(o.getData().getList_data());
            count = o.getData().getList_data().size();
        }
        number.setText(count + "");
    }

    @Override
    protected SearchPresent createPresenter() {
        return new SearchPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_position7);
        ButterKnife.bind(this);

        recyclerView1.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new CommonRecyclerAdapter<SerailBean1.DataBean>(mActivity, R.layout.item_search7, data) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, SerailBean1.DataBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.sn, item.getGoods_model());
                helper.setText(R.id.model, item.getGoods_name());
                helper.setText(R.id.name, item.getCase_code());
                helper.setText(R.id.code, item.getCount_num());

                helper.setOnClickListener(R.id.wx_code, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String type_two_status;
                        if ((int) type.getTag() == 0) {
                            type_two_status = ((int) zx_type.getTag() + 1) + "";
                        } else {
                            type_two_status = ((int) zx_type.getTag() + 3) + "";
                        }

                        startActivity(new Intent(SearchPositionActivity7.this, SearchPositionDetailActivity7.class)
                                .putExtra("order_sn", item.getOrder_sn())
                                .putExtra("keywords", item.getCase_code())
                                .putExtra("type", ((int) search_type.getTag() + 1) + "")
                                .putExtra("type_two", ((int) type.getTag() + 1) + "")
                                .putExtra("type_two_status", type_two_status)
                                .putExtra("goods_model", item.getGoods_model())
                                .putExtra("order_id", item.getOrder_id()));
                    }
                });
            }
        };
        recyclerView1.setAdapter(adapter);

        recyclerView2.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter2 = new CommonRecyclerAdapter<SerailBean1.DataBean>(mActivity, R.layout.item_search1, data2) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, SerailBean1.DataBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.sn, item.getCode());
                helper.setText(R.id.model, item.getGoods_model());
                helper.setText(R.id.name, item.getGoods_name());
                helper.setText(R.id.code, item.getCase_code());
                if ((int) type.getTag() == 1) {
                    helper.setText(R.id.wx_code, item.getUpdate_time());
                } else {
                    helper.setText(R.id.wx_code, item.getCreate_time());
                }

            }
        };
        recyclerView2.setAdapter(adapter2);

        initScan();
        timeView.setText("装箱时间");
        search_type.setTag(0);
        type.setTag(0);
        zx_type.setTag(0);
        setViewState();
//        onBarcodeEvent("CPCG202106250001");

    }

    @OnClick({R.id.iv_back, R.id.qingkong, R.id.qingkong2, R.id.chaxun, R.id.search_type, R.id.type, R.id.zx_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if (BaseUtils.fastClick()) {
                    finish();
                }
                break;
            case R.id.qingkong:
                text.setText("");
                number.setText("");
                text.setBackgroundResource(R.drawable.et_yellow);
                data.clear();
                adapter.clear();
                data2.clear();
                adapter2.clear();
                playRing("qingkong.mp3");
                break;
            case R.id.qingkong2:
                text2.setText("");
                if (!TextUtils.isEmpty(text.getText().toString().trim())) {
                    text2.setBackgroundResource(R.drawable.et_yellow);
                }
                number.setText("");
                data2.clear();
                adapter2.clear();
                playRing("qingkong.mp3");
                break;
            case R.id.chaxun:
                String type_two_status;
                if ((int) type.getTag() == 0) {
                    type_two_status = ((int) zx_type.getTag() + 1) + "";
                } else {
                    type_two_status = ((int) zx_type.getTag() + 3) + "";
                }
                if ((int) search_type.getTag() == 0 || (int) search_type.getTag() == 1) {
                    if (TextUtils.isEmpty(text.getText().toString().trim())) {
                        ToastUtil.getInstance()._short(SearchPositionActivity7.this, "凭证编号不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(text2.getText().toString().trim())) {
                        ToastUtil.getInstance()._short(SearchPositionActivity7.this, "查找内容不能为空");
                        return;
                    }
                    page = 1;

                    mPresenter.Into57(((int) search_type.getTag() + 1) + "", ((int) type.getTag() + 1) + "", type_two_status, text.getText().toString().trim(), text2.getText().toString().trim());
                } else {
                    if (TextUtils.isEmpty(text.getText().toString().trim())) {
                        ToastUtil.getInstance()._short(SearchPositionActivity7.this, "凭证编号不能为空");
                        return;
                    }
                    page = 1;
                    mPresenter.Into57(((int) search_type.getTag() + 1) + "", ((int) type.getTag() + 1) + "", type_two_status, text.getText().toString().trim(), "");
                }
                break;
            case R.id.search_type:
                XPopup.get(SearchPositionActivity7.this).asCenterList("请选择类型", new String[]{"SN", "外箱编码", "凭证编号"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text1) {
                                search_type.setText(text1);
                                search_type.setTag(position);
                                setViewState();
//                                onBarcodeEvent("CPCG202106250001");
                            }
                        })
                        .show();
                break;
            case R.id.type:
                XPopup.get(SearchPositionActivity7.this).asCenterList("请选择类型", new String[]{"装箱", "出库"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text1) {
                                type.setText(text1);
                                type.setTag(position);
                                setView1State();
//                                if(position==0) {
//                                    onBarcodeEvent("CP00000002");
//                                }else{
//                                    onBarcodeEvent("K4002akny022126C3569");
//                                }
                            }
                        })
                        .show();
                break;
            case R.id.zx_type:
                if ((int) type.getTag() == 0) {
                    XPopup.get(SearchPositionActivity7.this).asCenterList("请选择类型", new String[]{"已装箱", "未装箱"},
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text1) {
                                    zx_type.setText(text1);
                                    zx_type.setTag(position);
                                }
                            })
                            .show();
                } else {
                    XPopup.get(SearchPositionActivity7.this).asCenterList("请选择类型", new String[]{"已出库", "未出库"},
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text1) {
                                    zx_type.setText(text1);
                                    zx_type.setTag(position);
                                }
                            })
                            .show();
                }
                break;
        }
    }

    private void setViewState() {
        switch ((int) search_type.getTag()) {
            case 0:
            case 1:
                ll2.setVisibility(View.VISIBLE);
                ll_zx.setVisibility(View.GONE);
                ll_bm.setVisibility(View.GONE);
                llOther.setVisibility(View.VISIBLE);
                setView1State();
                break;
            default:
                ll2.setVisibility(View.GONE);
                ll_zx.setVisibility(View.VISIBLE);
                ll_bm.setVisibility(View.VISIBLE);
                llOther.setVisibility(View.GONE);
                setView1State();
                break;
        }
    }

    private void setView1State() {
        if ((int) type.getTag() == 0) {
            timeView.setText("装箱时间");
            if ((int) zx_type.getTag() == 0) {
                zx_type.setText("已装箱");
            } else {
                zx_type.setText("未装箱");
            }
        } else {
            timeView.setText("出库时间");
            if ((int) zx_type.getTag() == 0) {
                zx_type.setText("已出库");
            } else {
                zx_type.setText("未出库");
            }
        }
    }

    AidcManager manager;
    BarcodeReader barcodeReader;

    private void initScan() {
        //第一步：获取扫描资源，设置扫描参数，开启扫描功能
        AidcManager.create(this, new AidcManager.CreatedCallback() {
            @Override
            public void onCreated(AidcManager aidcManager) {
                manager = aidcManager;
                barcodeReader = manager.createBarcodeReader();
                try {
                    barcodeReader.claim(); //开启扫描功能
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //第二步：添加侧面扫描键事件监听和条码事件监听
                barcodeReader.addTriggerListener(SearchPositionActivity7.this);
                barcodeReader.addBarcodeListener(SearchPositionActivity7.this);
            }
        });
    }

    @Override
    public void onBarcodeEvent(BarcodeReadEvent barcodeReadEvent) {
        String barcodeData = barcodeReadEvent.getBarcodeData();
        System.out.println("扫描结果：" + barcodeData);
        if ((int) type.getTag() == 1 || (int) type.getTag() == 0) {
            if (TextUtils.isEmpty(text.getText().toString().trim())) {
                Message message = new Message();
                message.what = 1;
                message.obj = barcodeData;
                handler.sendMessage(message);
            } else {
                Message message = new Message();
                message.what = 2;
                message.obj = barcodeData;
                handler.sendMessage(message);
            }
        } else {
            Message message = new Message();
            message.what = 1;
            message.obj = barcodeData;
            handler.sendMessage(message);
        }
    }

    @Override
    public void onFailureEvent(BarcodeFailureEvent barcodeFailureEvent) {
        System.out.println("失败：");

    }

    @Override
    public void onTriggerEvent(TriggerStateChangeEvent triggerStateChangeEvent) {
        System.out.println("按键：");
        if (triggerStateChangeEvent.getState() == true) {
            try {
                barcodeReader.light(true);        //开启补光
                barcodeReader.aim(true);        //开启瞄准线
                barcodeReader.decode(true);        //开启解码
            } catch (Exception e) {
                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        } else if (triggerStateChangeEvent.getState() == false) {
            try {
                barcodeReader.light(false);        //关闭补光
                barcodeReader.aim(false);        //关闭瞄准线
                barcodeReader.decode(false);    //关闭解码
            } catch (Exception e) {
                Toast.makeText(this, "关闭扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();

    private void playRing(String fileName) {
        try {
            assetManager = getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playUrl(String fileName, final int i) {
        if (TextUtils.isEmpty(fileName)) {
            if (i == 1) {
                playRing("luruchenggong.mp3");
                return;
            } else {
                playRing("wuxiao.mp3");
                return;
            }
        }
        try {
            player.reset();
            if (!fileName.contains("http")) {
                player.setDataSource(BaseUrl.mp3Url + fileName);
            } else {
                player.setDataSource(fileName);
            }
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    if (i == 1) {
                        playRing("luruchenggong.mp3");
                    } else {
                        playRing("wuxiao.mp3");
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (barcodeReader != null) {
            try {
                barcodeReader.claim();        //开启扫描功能
            } catch (Exception e) {
                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (barcodeReader != null) {
            barcodeReader.release();        //释放扫描资源
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (barcodeReader != null) {
            barcodeReader.removeBarcodeListener(this);
            barcodeReader.removeTriggerListener(this);
            barcodeReader.close();
        }
        if (manager != null) {
            manager.close();
        }
    }
}
